import 'dart:async';
import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/device/domain/states/device_discovery_state.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

/// 设备发现服务（StateNotifier版本）
class DeviceDiscoveryNotifier extends StateNotifier<DeviceDiscoveryState> {
  Timer? _timeoutTimer;

  StreamSubscription? _discoverySub;
  final Set<String> _foundDeviceIds = {};

  // 添加StreamController用于对外暴露
  final _deviceStreamController =
      StreamController<ThingSmartDeviceModel>.broadcast();
  // 暴露Stream（永不断开）
  Stream<ThingSmartDeviceModel> get deviceStream =>
      _deviceStreamController.stream;

  DeviceDiscoveryNotifier() : super(const DeviceDiscoveryState());
  int startTime = 0;

  void _applyState(
    DeviceDiscoveryState Function(DeviceDiscoveryState) updater,
  ) {
    if (!mounted) return;
    state = updater(state);
  }

  /// 开始设备发现
  Future<void> discoverDevices({
    int timeOut = CommonConfig.discover_device_timeout,
  }) async {
    if (state.isSearching) {
      Log.i('🔄 重新开始设备搜索');
      await _stopDiscovery(clearCache: false, reason: '重新搜索');
    }

    Log.i('🚀 开始设备搜索流程...');
    startTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;

    _applyState(
      (prev) => prev.copyWith(devices: [], isSearching: true, error: null),
    );

    try {
      // 启动超时计时器
      if (timeOut > 0) {
        _timeoutTimer = Timer(Duration(seconds: timeOut), () {
          Log.w('⏰ 搜索超时: ${timeOut}s 到达');
          _stopDiscovery(clearCache: false, reason: '超时终止');
        });
      }

      // 开始设备发现
      _discoverySub = TuyaService().discoverDevices().listen(
        _handleDeviceFound,
        onError: _handleDiscoveryError,
        onDone: _handleDiscoveryDone,
      );
    } catch (e, st) {
      Log.e('❌ 启动设备搜索失败', e, st);
      if (mounted == false) {
        return;
      }

      _applyState(
        (prev) =>
            prev.copyWith(isSearching: false, error: '启动失败: ${e.toString()}'),
      );
      // rethrow;
    }
  }

  /// 停止设备发现
  Future<void> stopDiscovery({bool cleanCache = false}) async {
    await _stopDiscovery(clearCache: cleanCache, reason: '手动停止');
  }

  /// 处理发现的设备
  void _handleDeviceFound(ThingSmartDeviceModel device) {
    if (!state.isSearching) return;

    if (!_deviceStreamController.isClosed) {
      _deviceStreamController.add(device);

      // 去重检查
      if (_foundDeviceIds.contains(device.uuid)) {
        Log.d('🔄 忽略重复设备: ${device.name}');
        return;
      }
      final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;

      Log.i(
        '📱 发现设备: ${device.name} ⏱ 耗时: ${now - startTime}s, uuID: ${device.uuid}, pid: ${device.productId}, devId: ${device.devId}',
      );
      _foundDeviceIds.add(device.uuid);

      _applyState((prev) => prev.copyWith(devices: [...prev.devices, device]));
    }
  }

  /// 处理发现错误
  void _handleDiscoveryError(Object error, StackTrace stackTrace) {
    Log.e('🔴 设备搜索错误', error, stackTrace);
    _stopDiscovery(clearCache: false, reason: '错误: ${error.toString()}');
  }

  /// 处理发现完成
  void _handleDiscoveryDone() {
    Log.i('✅ 设备搜索正常完成');
    _stopDiscovery(clearCache: false, reason: '正常完成');
  }

  /// 安全停止发现
  Future<void> _stopDiscovery({
    required bool clearCache,
    required String reason,
  }) async {
    if (!state.isSearching) return;

    Log.i('🛑 停止设备搜索 (原因: $reason)');

    // 取消所有计时器
    _timeoutTimer?.cancel();
    _timeoutTimer = null;

    startTime = 0;
    // 取消订阅
    await _discoverySub?.cancel();
    _discoverySub = null;
    _foundDeviceIds.clear();
    // 停止SDK搜索
    try {
      await TuyaService().discoverStop(cleanCache: clearCache);
    } catch (e, st) {
      Log.e('⚠️ 停止SDK搜索时出错', e, st);
    }
    if (mounted == false) {
      return;
    }
    _applyState(
      (prev) => prev.copyWith(
        isSearching: false,
        error: reason.contains('错误') ? reason : null,
      ),
    );
    // 更新状态
  }

  /// 清空设备列表
  void clearDevices() {
    Log.i('♻️ 清空设备列表');
    _foundDeviceIds.clear();

    _applyState((prev) => prev.copyWith(devices: const []));
  }

  /// 移除特定设备(解决某一设备配网完成后返回，发现列表中依然有该设备的问题)
  void removeDeviceList(Set<String> uuidSet) {
    _foundDeviceIds.removeAll(uuidSet);

    _applyState(
      (prev) => prev.copyWith(
        devices: prev.devices
            .where((d) => uuidSet.contains(d.uuid) == false)
            .toList(),
      ),
    );
  }

  /// 释放资源
  @override
  void dispose() {
    Log.i('♻️ 释放DeviceDiscoveryNotifier资源');
    clearDevices();
    _stopDiscovery(clearCache: true, reason: 'Notifier销毁');
    _timeoutTimer?.cancel();

    _discoverySub?.cancel();
    _deviceStreamController.close(); // 清理资源
    super.dispose();
  }
}
